#!/usr/bin/env python
# -*- coding: utf-8 -*-

from aiohttp import ClientSession, hdrs

class Client:

    def __init__(self, url, app=None,client=None, **kwargs):
        self._url = url
        self._client = client if client else ClientSession(loop=app.loop, **kwargs)

    def cli(self):
        # self.handler_url()
        return ClientSessionConn(self._client, url=self._url)

    def close(self):
        self._client.close()


class ClientSessionConn:
    _client = None

    def __init__(self, client, url=None, **kwargs):
        self._client = client
        self._url = url

    def handler_url(self, url):
        if url.startswith("http"):
            return url
        if self._url:
            return "{}/{}".format(self._url, url)
        return url

    def before(self, method, url):
        self._span.log_kv({'event': 'client'})
        self._span.set_tag('http.url', self._url)
        self._span.set_tag('http.path', url)
        self._span.set_tag('http.method', method)
        http_header_carrier = {}
        # opentracing.tracer.inject(
        #     self._span.context,
        #     format=opentracing.Format.HTTP_HEADERS,
        #     carrier=http_header_carrier)
        return http_header_carrier


    def request(self, method, url, **kwargs):
        headers = self.before(method, url)
        res = self._client.request(method, self.handler_url(url),
                                   headers=headers, **kwargs)
        self._span.set_tag('component', 'http-client')
        self._span.finish()
        return res

    def get(self, url, allow_redirects=True, **kwargs):
        return self.request(hdrs.METH_GET, url, allow_redirects=True,
                       **kwargs)

    def post(self, url, data=None, **kwargs):
        return self.request(hdrs.METH_POST, url, data=data, **kwargs)

    def put(self, url, data=None, **kwargs):
        return self.request(hdrs.METH_PUT, url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        return self.request(hdrs.METH_DELETE, url, **kwargs)

    def head(self, url, allow_redirects=False, **kwargs):
        return self.request(hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs)

    def options(self, url, allow_redirects=True, **kwargs):
        return self.request(hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs)

    def close(self):
        self._client.close()
